<template>
    <van-form @submit="onSubmit"  @failed="onFailed" >
        <van-field
            v-model="form.username"
            name="username"
            clearable
            left-icon="user-o"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
            v-model="form.password"
            :type="type"
            name="password"
            clearable
            left-icon="warn-o"
            label="密码"
            placeholder="密码"
            :rules="[
                { required: true, message: '请填写密码' },
                { pattern:reg.pwd, message:'请输入正确的密码(6-16位的数字和字母)'}
            ]"
            :right-icon="type!='password'?'eye-o':'closed-eye'"
            @click-right-icon="changeType"
        />
        <div style="margin: 16px 0;" class="links">
            <router-link :to="{name:'register'}" class="aitem color1 " >没有账号,请注册</router-link>
            <router-link :to="{name:'forgetpass'}" class="aitem color2 " >找回密码</router-link>
        </div>
        <div style="margin: 16px 0;">
            <van-button  block type="info" native-type="submit">登录</van-button>
            <van-button class="mt20" block type="danger" native-type="reset">重置</van-button>
        </div>
    </van-form>
</template>

<script>
export default {
    data(){
        return {
            form:{},
            type:"password"
        }
    },
    methods:{
        onFailed(){
            this.showFailMsg('请输入有效的登录信息')
        },
        async onSubmit(value){
            console.log(value)
            let res = await this.$ajax.findUser(value);
            console.log(res)
            if(res.length>0){
                this.ShowSuccess('登录成功');
                localStorage.setItem('username',value.username);
                
                this.changeUserInfo(res[0])  // 存储全局的用户信息 
                if(this.$route.query.from){
                    // 直接返回
                    this.$router.back();
                }else{
                    this.$router.push({name:"mine"})
                }
            }else{
                this.showFailMsg('登录失败')
            }
        },
        changeType(){
            this.type = this.type=='password'?'text':'password'
        }
    },
    mounted(){
        // 判断是否存储了username 
        if(this.$route.query.username){
            this.form = {...this.form,username:this.$route.query.username}
        }else{
             this.form = {...this.form,username:localStorage.getItem('username')}
        }
    }
}
</script>

<style lang="scss" scoped>
.mt20{
    margin-top:10px;
}
</style>